package com.lihao.wanandroid.ui.home.plaza

import android.os.Bundle
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.kingja.loadsir.core.LoadService
import com.lihao.jetpackcore.ext.getViewModel
import com.lihao.jetpackcore.ext.nav
import com.lihao.jetpackcore.ext.parseState
import com.lihao.jetpackcore.ext.util.dp2px
import com.lihao.jetpackcore.util.ToastUtil
import com.lihao.wanandroid.R
import com.lihao.wanandroid.app.base.BaseFragment
import com.lihao.wanandroid.app.ext.*
import com.lihao.wanandroid.app.util.VibrateUtils
import com.lihao.wanandroid.app.weight.recyclerview.SpaceItemDecoration
import com.lihao.wanandroid.data.model.CollectEvent
import com.lihao.wanandroid.ui.collect.CollectViewModel
import com.lihao.wanandroid.ui.web.WebFragment
import kotlinx.android.synthetic.main.fragment_plaza.*

/**
 * Created by lihao on 2020/6/12.
 * Describe: 广场Fragment
 */
class PlazaFragment : BaseFragment<PlazaViewModel>() {

    private lateinit var loadSir: LoadService<Any>

    val collectViewModel: CollectViewModel by lazy {
        getViewModel<CollectViewModel>()
    }

    private val mAdapter: PlazaAdapter by lazy {
        PlazaAdapter().apply {
            setAdapterAnimation(2)
            loadMoreModule.setOnLoadMoreListener {
                mViewModel.getPlazaData(false)
            }
            setOnItemClickListener { adapter, view, position ->
                val bundle = Bundle().apply {
                    putParcelable(WebFragment.KEY_ARTICLE, mAdapter.data[position])
                }
                nav().navigate(R.id.action_to_webFragment, bundle)
            }
            setOnItemChildClickListener { adapter, view, position ->
                when (view.id) {
                    R.id.tvCollect -> {
                        VibrateUtils.vibrate(40)
                        if (shareViewModel.isLogin.value) {
                            if (mAdapter.data[position].collect) {
                                collectViewModel.uncollectArticle(mAdapter.data[position].id)
                            } else {
                                collectViewModel.collectArticleIn(mAdapter.data[position].id)
                            }
                        } else {
                            nav().navigate(R.id.action_to_loginFragment)
                        }
                    }
                }
            }
        }
    }

    override fun layoutId() = R.layout.fragment_plaza

    override fun initView(savedInstanceState: Bundle?) {
        loadSir = LoadServiceInit(recyclerView) {
            loadSir.showLoading()
            mViewModel.getPlazaData(true)
        }
        recyclerView.init(LinearLayoutManager(context), mAdapter).run {
            addItemDecoration(SpaceItemDecoration(dp2px(8), dp2px(8)))
        }
        swipeRefresh.setOnRefreshListener {
            mViewModel.getPlazaData(true)
        }
    }

    override fun lazyLoadData() {
        loadSir.showLoading()
        mViewModel.getPlazaData(true)
    }

    override fun createObserver() {
        mViewModel.plazaData.observe(this, Observer { resultState ->
            parseState(resultState, {
                mViewModel.pageNo++
                swipeRefresh.isRefreshing = false
                when {
                    it.isFirstEmpty() -> {
                        loadSir.showEmpty()
                    }
                    it.isRefresh() -> {
                        loadSir.showSuccess()
                        mAdapter.setList(it.datas)
                    }
                    else -> {
                        loadSir.showSuccess()
                        mAdapter.addData(it.datas)
                        if (it.hasMore())
                            mAdapter.loadMoreModule.loadMoreComplete()
                        else
                            mAdapter.loadMoreModule.loadMoreEnd()
                    }
                }
            }, {
                if (mViewModel.pageNo.isRefresh()) {
                    swipeRefresh.isRefreshing = false
                    loadSir.showError(it.errorMsg)
                } else {
                    mAdapter.loadMoreModule.loadMoreFail()
                }
            })
        })

        collectViewModel.collectState.observe(this, Observer {
            if (it.isSuccess) {
                ToastUtil.showShort(context, if(it.collect) "收藏成功！" else "取消收藏！")
                eventViewModel.collect.value = CollectEvent(it.id, it.collect)
            } else {
                ToastUtil.showShort(context, it.errorMsg)
            }
        })
        shareViewModel.run {
            userInfo.observe(viewLifecycleOwner, Observer {
                if (it != null) {
                    it.collectIds.forEach { id ->
                        for (item in mAdapter.data) {
                            if (id.toInt() == item.id) {
                                item.collect = true
                                break
                            }
                        }
                    }
                } else {
                    for (item in mAdapter.data) {
                        item.collect = false
                    }
                    mAdapter.notifyDataSetChanged()
                }
            })
        }
        eventViewModel.collect.observe(this, Observer {
            for (index in mAdapter.data.indices) {
                if (mAdapter.data[index].id == it.id) {
                    mAdapter.data[index].collect = it.collect
                    mAdapter.notifyDataSetChanged()
                    break
                }
            }
        })
    }
}